package com.tanhua.server.controller;

import com.tanhua.model.vo.ErrorResult;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@RestController
@RequestMapping("/user")
public class LoginController {

    @Autowired
    private UserService userService;

    /**
     * 用户登录
     * 参数：phone 类型：String
     * 响应：无返回值，void
     */
    @PostMapping("/login")
    public ResponseEntity login(@RequestBody Map map) {
        String phone = (String) map.get("phone");
        userService.sendMsg(phone);
//        return ResponseEntity.status(500).body("数据出错了！");
        return ResponseEntity.ok(null);
    }

    /**
     * 校验验证码实现登录
     * 请求路径：/user/loginVerification
     * 请求方式：POST
     * 请求参数：phone和 verificationCode
     */
    @PostMapping("/loginVerification")
    public ResponseEntity loginVerification(@RequestBody Map map) {
        try {
            //从map集合中获取数据
            String phone = (String) map.get("phone");
            String code = (String) map.get("verificationCode");
            //调用userService的方法，返回一个map对象
            Map retmap = userService.loginVerification(phone, code);
            return ResponseEntity.ok(retmap);
        }catch (BusinessException e){
            ErrorResult errorResult = e.getErrorResult();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResult);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(ErrorResult.error());
        }
    }
}
